package com.topisv.tms.web.lead;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.CustomerLead;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.service.CustomerLeadService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.utils.lead.LeadUtil;
import com.topisv.tms.web.base.BaseController;

@Controller
@RequestMapping(value = "/leadSkuMasterplate")
public class LeadSkuController extends BaseController{

	private static final Logger log = LoggerFactory.getLogger(LeadSkuController.class);
	
	private final static String values = "lead/leadEdiOrderValues";
	
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	@Autowired
	private CustomerLeadService customerLeadService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "leadSku/{customerCode}/{updateType}")
	public String leadSku(@PathVariable(value = "customerCode") String customerCode,@PathVariable(value = "updateType") String updateType,@RequestParam(value = "overWrite",required=false) Boolean overWrite,Model model,
			ServletRequest request, RedirectAttributes redirectAttributes) {
		HttpServletRequest httpRequest = null;
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		List<FileItem> items = null;
		Workbook rwb = null;
		InputStream stream = null;
		if(null == overWrite)overWrite = Boolean.FALSE;
		try {

			httpRequest = (HttpServletRequest) request;
			httpRequest.setCharacterEncoding("UTF-8");
			factory = new DiskFileItemFactory();
			upload = new ServletFileUpload(factory);
			model.addAttribute("status", "2");
			items = upload.parseRequest(httpRequest);
			Iterator<FileItem> itr = items.iterator();
			CustomerLead customerLead=this.customerLeadService.findByCustomerCodeAndOrdenoSource(customerCode, updateType);
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {

				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						List<EdiGoodsSku> ediGoodsSkus = new ArrayList<EdiGoodsSku>();
						// 获取Excel文件对象
						stream = item.getInputStream();

						if (item.getName().endsWith(".xls")) {// 解析xls
							rwb = new HSSFWorkbook(stream);
							int count = rwb.getNumberOfSheets();
							for (int i = 0; i < count; i++) {
								Sheet sheet = rwb.getSheetAt(i);
								int rows=sheet.getLastRowNum();
								if(rows>0){
									ediGoodsSkus.addAll(LeadUtil.getEdiGoodsSkus(customerLead,customerCode,sheet));
								}
							}
						} else if (item.getName().endsWith(".xlsx")) {// 解析xlsx
							rwb = new XSSFWorkbook(stream);
							int count = rwb.getNumberOfSheets();
							for (int i = 0; i < count; i++) {
								XSSFSheet sheet = (XSSFSheet) rwb.getSheetAt(i);
								int rows=sheet.getLastRowNum();
								if(rows>0){
								  ediGoodsSkus.addAll(LeadUtil.getEdiGoodsSkus(customerLead,customerCode,sheet));
								}
							}
						}
						Map<String, List<EdiGoodsSku>> maps=ediGoodsSkuService.save(customerCode,ediGoodsSkus,overWrite);
						
						model.addAttribute("normal", maps.get("normal"));
						model.addAttribute("exception", maps.get("exception"));
						model.addAttribute("number", maps.get("exception").size()+maps.get("normal").size());
						model.addAttribute("message", "商品信息导入成功");
						
					} else {
						model.addAttribute("message", "请提供商品信息数据文件");
					}
				}
			}
		} catch (Exception e) {
			log.error("LeadSkuController case error.",e);
			model.addAttribute("message", "服务器异常，导入数据失败，如果重试还是这样请联系开发技术支持");
		} finally {
			if (null != stream) {
				try {
					stream.close();
				} catch (IOException e) {
					log.info("out of memory");
				}
			}
		}
		
		return values;
	}
	
	public static void main(String[] args) throws Exception, IOException {
		List<EdiGoodsSku> ediGoodsSkus =new ArrayList<EdiGoodsSku>();
		HSSFWorkbook rwb = new HSSFWorkbook(new FileInputStream("d:\\t.xls"));
			int count = rwb.getNumberOfSheets();
			for (int i = 0; i < count; i++) {
				Sheet sheet = rwb.getSheetAt(i);
				int rows=sheet.getLastRowNum();
				if(rows>0){
					ediGoodsSkus.addAll(LeadUtil.getEdiGoodsSkus(null,"MID",sheet));
				}
	}
			for (EdiGoodsSku ediGoodsSku : ediGoodsSkus) {
				log.info("@XmlElement(name = \""+ediGoodsSku.getSku().trim()+"\")");
				log.info("private String "+ediGoodsSku.getSku().trim()+";");
			}
	}
}
